from pyglet.gl import *
import random

class Particle:
    MinSize = 10
    MaxSize = 25
    MinAlpha = 0.2
    MaxAlpha = 0.8

    def __init__(self, pos, vel, texid = 0, sizedt = 1):
        self.pos = pos
        factor = random.randint(1, 4)
        self.vel = (vel[0]/factor, vel[1]/factor)
        self.angle = 0 #random.randint(30, 60)
        self.adt = random.choice([-1, 1])
        self.texid = texid 
        self.sizedt = sizedt 
        if sizedt > 0:
            self.size = Particle.MinSize
            self.alpha = Particle.MaxAlpha
        else:
            self.size = Particle.MaxSize
            self.alpha = Particle.MinAlpha

    def update(self, dt):
        self.pos = (self.pos[0]+ dt*self.vel[0], self.pos[1]+dt*self.vel[1])
        self.angle += 60 * dt * self.adt;
        self.alpha -= self.sizedt * dt                
        self.size += self.sizedt

    def render(self):
        pos = self.pos
        w = self.size
        glColor4f(1, 1, 1, self.alpha)
        glBindTexture(GL_TEXTURE_2D, self.texid)
        glPushMatrix()
        glTranslatef(pos[0], pos[1], 0)
        glRotatef(self.angle, 0, 0, 1)
        glTranslatef(-pos[0], -pos[1], 0)
        glBegin(GL_POLYGON)
        glTexCoord2f(0, 0)
        glVertex2f(pos[0]-w, pos[1]-w)
        glTexCoord2f(0, 1)
        glVertex2f(pos[0]-w, pos[1]+w)
        glTexCoord2f(1, 1)
        glVertex2f(pos[0]+w, pos[1]+w)
        glTexCoord2f(1, 0)
        glVertex2f(pos[0]+w, pos[1]-w)
        glEnd()
        glPopMatrix()

class Blast:
    def __init__(self, pos, texid, repeat=True, len=3):
        self.particles = []
        self.pos = pos
        self.texid = texid
        self.repeat = repeat 
        self.done = False
        self.len = len
        s = 40
        vlist = ((-s, 0), (s, s), (-s, -s), (0,-s), (s, 0), (0,s))
        for i in xrange(len):
            self.particles.append(Particle(pos, random.choice(vlist), texid))

    def update(self, dt):
        for p in self.particles:
            p.update(dt)
            if p.size > 2*Particle.MaxSize:
                self.particles.remove(p)
        if self.repeat and len(self.particles) < self.len :
            s = 40
            vlist = ((-s, 0), (s, s), (-s, -s), (0,-s), (s, 0), (0,s))
            self.particles.append(Particle(self.pos, random.choice(vlist), self.texid))
        if len(self.particles) == 0:
            self.done = True


    def render(self):
        for p in self.particles:
            p.render()
        glColor4f(1, 1, 1, 1)
